package nl.zeeman.planner;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Calendar;

import android.app.AlertDialog;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class planner extends Activity {
    /** Called when the activity is first created. */
	public static final String PREFS_NAME = "PlannerPrefs";
	public static final String PREFS_SITE = "Location";
	public static final int INVALID_POSITION = -1; 
	public static int mYear;
	public static int mMonth;
	public static int mDay;
	
	// define column names. This way we can easily change de database
	// names without having to go through all the code
	private final String COL_SITE_NAME = "name";
	private final String COL_SITE_HT_CORR = "HighTideCorrection";
	private final String COL_SITE_LT_CORR = "LowTideCorrection";
	private final String COL_SITE_HT_DIVE_ALLOWED = "DiveAtHighTide";
	private final String COL_SITE_LT_DIVE_ALLOWED = "DiveAtLowTide";
	private final String COL_SITE_EXTRAINFO = "ExtraInfo";

	private final String COL_DATE_TIME = "diveTime";
	private final String COL_DATE_HT = "isHighTide";
	private final String COL_DATE_NAP = "CmTovNAP";
	private final String COL_DATE_MOON = "MoonPhase";
	
	// UI references
	private Spinner mSpinSite;
		
	private DatePicker mDatePicker;
	private Button mTable;
	private TextView mInfo;
	private TextView mLblTime;
	private TextView mLblTide;
	private TextView mLblNAP;
	private TextView mLblTxt;
	private TextView mTime1;
	private TextView mTide1;
	private TextView mNAP1;
	private TextView mTxt1;
	private TextView mTime2;
	private TextView mTide2;
	private TextView mNAP2;
	private TextView mTxt2;
	private TextView mTime3;
	private TextView mTide3;
	private TextView mNAP3;
	private TextView mTxt3;
	private TextView mTime4;
	private TextView mTide4;
	private TextView mNAP4;
	private TextView mTxt4;

	private TextView mSiteInfo;

	static final int DATE_DIALOG_ID = 0;
	
	public static PlannerDatabaseAdapter myDBHelper;
	
	// create the menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
		
	//define the menu actions
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.itmAbout:
	        ShowAbout();
	        return true;
//	    case R.id.itmTable:
//	    	ShowDiveTable();
//	    	return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Initialize();
        
	}

	public void onResume(){
		super.onResume();
		
        myDBHelper = new PlannerDatabaseAdapter(this);
        myDBHelper.open();	
	}
	
    protected void onStop(){
        super.onStop();
     
       // Save user preferences. We need an Editor object to
       // make changes. All objects are from android.context.Context
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       SharedPreferences.Editor editor = settings.edit();
       editor.putInt(PREFS_SITE, (int) mSpinSite.getSelectedItemId());
       
       // Don't forget to commit your edits!!!
       editor.commit();

       myDBHelper.close();
       
    }

    protected void onPause(){
    	super.onPause();
/*    	
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(PREFS_SITE, (int) mSpinSite.getSelectedItemId());
        
        // Don't forget to commit your edits!!!
        editor.commit();
    	
        myDBHelper.close();
*/        
    }

    // clear site info
    private void InitScreen() {
		mLblTime.setText("");
		mLblTide.setText("");
		mLblNAP.setText("");
		mLblTxt.setText("");
    	
		mTime1.setText("");
		mTide1.setText("");
		mNAP1.setText("");
		mTxt1.setText("");

		mTime2.setText("");
		mTide2.setText("");
		mNAP2.setText("");
		mTxt2.setText("");

		mTime3.setText("");
		mTide3.setText("");
		mNAP3.setText("");
		mTxt3.setText("");

		mTime4.setText("");
		mTide4.setText("");
		mNAP4.setText("");
		mTxt4.setText("");
    }
    
    private void Initialize(){
        setContentView(R.layout.main);

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        
        ProgressDialog dialog = ProgressDialog.show(this, "", 
                getResources().getString(R.string.lblLoading), true);
        
        // get UI references
        mDatePicker = (DatePicker) findViewById(R.id.dateDive);
        mSpinSite = (Spinner) findViewById(R.id.spinSite);
        mTable = (Button) findViewById(R.id.btnTable);
        mInfo = (TextView) findViewById(R.id.txtInfo);
        mLblTime = (TextView) findViewById(R.id.lblTime1);
        mTime1 = (TextView) findViewById(R.id.lblTime2);
        mTime2 = (TextView) findViewById(R.id.lblTime3);
        mTime3 = (TextView) findViewById(R.id.lblTime4);
        mTime4 = (TextView) findViewById(R.id.lblTime5);

        mLblTide = (TextView) findViewById(R.id.lblTide1);
        mTide1 = (TextView) findViewById(R.id.lblTide2);
        mTide2 = (TextView) findViewById(R.id.lblTide3);
        mTide3 = (TextView) findViewById(R.id.lblTide4);
        mTide4 = (TextView) findViewById(R.id.lblTide5);

        mLblNAP = (TextView) findViewById(R.id.lblNAP1);
        mNAP1 = (TextView) findViewById(R.id.lblNAP2);
        mNAP2 = (TextView) findViewById(R.id.lblNAP3);
        mNAP3 = (TextView) findViewById(R.id.lblNAP4);
        mNAP4 = (TextView) findViewById(R.id.lblNAP5);

        mLblTxt = (TextView) findViewById(R.id.lblText1);
        mTxt1 = (TextView) findViewById(R.id.lblText2);
        mTxt2 = (TextView) findViewById(R.id.lblText3);
        mTxt3 = (TextView) findViewById(R.id.lblText4);
        mTxt4 = (TextView) findViewById(R.id.lblText5);

        mSiteInfo = (TextView) findViewById(R.id.lblSiteInfo);

        // get the current date
        final Calendar cal = Calendar.getInstance();
        Calendar tempCalendar = Calendar.getInstance();
        tempCalendar.set(2012, 3, 1, 0, 0, 0);
        if(cal.after(tempCalendar)){
			Toast toast = Toast.makeText(planner.this, R.string.txtEndOfLife, Toast.LENGTH_LONG);
        	toast.show();
            finish();
        }
        
        mYear = cal.get(Calendar.YEAR);
        mMonth = cal.get(Calendar.MONTH);
        mDay = cal.get(Calendar.DAY_OF_MONTH);
        
        ArrayAdapter <CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        // open a reference to the database
        myDBHelper = new PlannerDatabaseAdapter(this);
        myDBHelper.open();
     	
        // get all available sites to show in the spinner
     	Cursor c =  myDBHelper.GetSiteNames();
     	if (c == null){
     		finish();
     	} else {
     		int NameColumn = c.getColumnIndex(COL_SITE_NAME);
     		c.moveToFirst();
     		do {
     			adapter.add(c.getString(NameColumn));
     		} while (c.moveToNext());
     		c.close();
     	}
     	mSpinSite.setAdapter(adapter);

     	//set last used dive location
        int loc = settings.getInt(PREFS_SITE, 0);

        try {
            mSpinSite.setSelection(loc);			
		} catch (Exception e) {
			// just ignore, if the last used location can't be set
		}

		// add a listener to the site spinner
		mSpinSite.setOnItemSelectedListener(new MyOnItemSelectedListener());
        mDatePicker.init(mYear, mMonth, mDay, new OnDateChangedListener() {
        	//@Override
        	public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
        		if (isDateAfter(view)){
        			Toast toast = Toast.makeText(planner.this, R.string.txtEndOfLife, Toast.LENGTH_LONG);
        			toast.show();
        			view.init(mYear, mMonth, mDay, this);
        		}else{
	        		if (isDateBefore(view)){
	        			view.init(mYear, mMonth, mDay, this);
	        		}else{
		        		mYear = mDatePicker.getYear();
		        		mMonth = mDatePicker.getMonth();
		        		mDay = mDatePicker.getDayOfMonth();
		        		ShowPlanner();
	        		}
        		}
        	}
        	
        	private boolean isDateAfter(DatePicker tempView) {
                Calendar mCalendar = Calendar.getInstance();
                mCalendar.set(2012, 3, 1, 0, 0, 0);
                Calendar tempCalendar = Calendar.getInstance();
                tempCalendar.set(tempView.getYear(), tempView.getMonth(), tempView.getDayOfMonth(), 0, 0, 0);
                if(tempCalendar.after(mCalendar))
                    return true;
                else 
                    return false;
            }
        	private boolean isDateBefore(DatePicker tempView) {
                Calendar mCalendar = Calendar.getInstance();
                mCalendar.set(2012, 0, 1, 0, 0, 0);
                Calendar tempCalendar = Calendar.getInstance();
                tempCalendar.set(tempView.getYear(), tempView.getMonth(), tempView.getDayOfMonth(), 0, 0, 0);
                if(tempCalendar.before(mCalendar))
                    return true;
                else 
                    return false;
            }
    	});
        
        mTable.setOnClickListener(mClickListener);
        
        dialog.dismiss();

    }

    // listener for the site spinner
    public class MyOnItemSelectedListener implements OnItemSelectedListener {

        public void onNothingSelected(AdapterView<?> parent) {
          // Do nothing.
        }

		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
        	ShowPlanner();
			
		}
    }
    
    // listener for the table button
    private OnClickListener mClickListener = new OnClickListener() {
		
		public void onClick(View v) {
			ShowDiveTable();
		}
	};

    // show site planning info
    private void ShowPlanner() {
    	
    	if (mSpinSite.getSelectedItemPosition()==INVALID_POSITION){
    		return;
    	}
    	
    	InitScreen();
    	 
    	// get tide info for the selected site
    	Cursor c = myDBHelper.GetSiteDetails(mSpinSite.getSelectedItem().toString());
    	if ( c == null) {
    		mInfo.setText(getResources().getString(R.string.txtNoSuchSite) + mSpinSite.getSelectedItem().toString());
    	} else {

    		// use entered date to create a calendar object for formatting and easier 
    		// date calculations
    		Calendar divetime = Calendar.getInstance();
    		DateFormat df = new SimpleDateFormat("E d-M-yyyy");
    		divetime.set(mYear, mMonth, mDay);
    		df.setCalendar(divetime);
    		
    		String sDate = null;
    		// format the date to a readable format
    		sDate = df.format(divetime.getTime());

    		mInfo.setText(getResources().getString(R.string.lblHeader).replaceAll("@DATE", sDate).replaceAll("@SITE", mSpinSite.getSelectedItem().toString()));
    		int HTCorrColumn = c.getColumnIndex(COL_SITE_HT_CORR);
    		int LTCorrColumn = c.getColumnIndex(COL_SITE_LT_CORR);
    		int HTAllowColumn = c.getColumnIndex(COL_SITE_HT_DIVE_ALLOWED);
    		int LTAllowColumn = c.getColumnIndex(COL_SITE_LT_DIVE_ALLOWED);
    		int SiteInfoColumn = c.getColumnIndex(COL_SITE_EXTRAINFO);
    		
    		c.moveToFirst();
    		Integer HTCorr = Integer.valueOf(c.getInt(HTCorrColumn));

    		//check if tide correction info is available for this site
    		boolean HTCorrFlag = !c.isNull(HTCorrColumn);
    		boolean LTCorrFlag = !c.isNull(LTCorrColumn);
    		Integer LTCorr = Integer.valueOf(c.getInt(LTCorrColumn));
    		Boolean HTAllow = (c.getInt(HTAllowColumn) == 1);
    		Boolean LTAllow = (c.getInt(LTAllowColumn) == 1);
    		String ExtraInfo = c.getString(SiteInfoColumn);

    		mSiteInfo.setText(ExtraInfo);
    		
    		// get tidal info for the specified date
    		df = new SimpleDateFormat("yyyy-MM-dd");
    		c = myDBHelper.GetDateInfo(df.format(divetime.getTime()));
    		if ( c == null) {
        		mInfo.setText(getResources().getString(R.string.txtNoSuchDate) + df.format(divetime.getTime()));
        	} else {
        		mLblTime.setText(R.string.lblTime);
        		mLblTide.setText(R.string.lblTide);
        		mLblNAP.setText(R.string.lblNAP);
        		mLblTxt.setText(R.string.lblTxt);
        		
        		int TimeColumn = c.getColumnIndex(COL_DATE_TIME);
         		int HTColumn = c.getColumnIndex(COL_DATE_HT);
         		int NAPColumn = c.getColumnIndex(COL_DATE_NAP);
         		int MoonColumn = c.getColumnIndex(COL_DATE_MOON);
         		int i = 0;
         		c.moveToFirst();
         		
         		String moon = c.getString(MoonColumn);
         		String moontext = "";
         		
         		if (moon.equals("NM")) {
         			moontext = getResources().getString(R.string.txtMoon).replace("@MOON", getResources().getString(R.string.txtNewMoon));
         		}
         		else if (moon.equals("VM")) {
         			moontext = getResources().getString(R.string.txtMoon).replace("@MOON", getResources().getString(R.string.txtFullMoon));
         		}
         		else if (moon.equals("NM+2")) {
         			moontext = getResources().getString(R.string.txtMoonPlusTwo).replace("@MOON", getResources().getString(R.string.txtNewMoon));
         		}
         		else if (moon.equals("NM+1")) {
         			moontext = getResources().getString(R.string.txtMoonPlusOne).replace("@MOON", getResources().getString(R.string.txtNewMoon));
         		}
         		else if (moon.equals("NM-1")) {
         			moontext = getResources().getString(R.string.txtMoonMinusOne).replace("@MOON", getResources().getString(R.string.txtNewMoon));
         		}
         		else if (moon.equals("NM-2")) {
         			moontext = getResources().getString(R.string.txtMoonMinusTwo).replace("@MOON", getResources().getString(R.string.txtNewMoon));
         		}
         		else if (moon.equals("VM+2")) {
         			moontext = getResources().getString(R.string.txtMoonPlusTwo).replace("@MOON", getResources().getString(R.string.txtFullMoon));
         		}
         		else if (moon.equals("VM+1")) {
         			moontext = getResources().getString(R.string.txtMoonPlusOne).replace("@MOON", getResources().getString(R.string.txtFullMoon));
         		}
         		else if (moon.equals("VM-1")) {
         			moontext = getResources().getString(R.string.txtMoonMinusOne).replace("@MOON", getResources().getString(R.string.txtFullMoon));
         		}
         		else if (moon.equals("VM-2")) {
         			moontext = getResources().getString(R.string.txtMoonMinusTwo).replace("@MOON", getResources().getString(R.string.txtFullMoon));
         		}
         		if (mSiteInfo.length() > 0) {
         			moontext = ". " + moontext;
         		}
         		
         		mSiteInfo.setText(mSiteInfo.getText() + moontext);
         		// get all tidal records
         		do {
         			i++;
         			df = new SimpleDateFormat("kk:mm");
         			String sText;
					if ((c.getInt(HTColumn) == 1 && !HTAllow) || (c.getInt(HTColumn) != 1 && !LTAllow)) {
						sText = getResources().getString(R.string.txtNoDive);
					}else{
						sText = "";
					}
         			try {
         				String timestring = c.getString(TimeColumn);
						divetime.setTime(df.parse(timestring));
						boolean CorrFlag;
						if (c.getInt(HTColumn) == 1) {
							divetime.add(Calendar.MINUTE, HTCorr);
							CorrFlag = HTCorrFlag;
						}else{
							divetime.add(Calendar.MINUTE, LTCorr);
							CorrFlag = LTCorrFlag;
						}
						df = new SimpleDateFormat("k:mm");
	         			//dit kan vast handiger!
	         			switch (i) {
						case 1:
							
							mTime1.setText(CorrFlag ? df.format(divetime.getTime()) : "-");
							mTide1.setText(getResources().getStringArray(R.array.lblTides)[c.getInt(HTColumn)]);
							mNAP1.setText(c.getString(NAPColumn));
							mTxt1.setText(sText);
							break;

						case 2:
							mTime2.setText(CorrFlag ? df.format(divetime.getTime()): "-");
							mTide2.setText(getResources().getStringArray(R.array.lblTides)[c.getInt(HTColumn)]);
							mNAP2.setText(c.getString(NAPColumn));
							mTxt2.setText(sText);
							
							break;

						case 3:
							mTime3.setText(CorrFlag ? df.format(divetime.getTime()): "-");
							mTide3.setText(getResources().getStringArray(R.array.lblTides)[c.getInt(HTColumn)]);
							mNAP3.setText(c.getString(NAPColumn));
							mTxt3.setText(sText);
							
							break;

						case 4:
							mTime4.setText(CorrFlag ? df.format(divetime.getTime()) : "-");
							mTide4.setText(getResources().getStringArray(R.array.lblTides)[c.getInt(HTColumn)]);
							mNAP4.setText(c.getString(NAPColumn));
							mTxt4.setText(sText);
							
							break;

						default:
							break;
						}
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						divetime.clear();
					}
         			
         		} while (c.moveToNext());
         		c.close();
        	}
    	}	
    }
    
    // show the about dialog
    public void ShowAbout() {
    	PackageInfo pInfo = null;
    	
    	try {
    		pInfo = getPackageManager().getPackageInfo("nl.zeeman.planner", PackageManager.GET_META_DATA);
    	
    	         } catch (NameNotFoundException e) {
    	                 e.printStackTrace();}
    	
    	String sVersion  = pInfo.versionName;
    	
    	AlertDialog ad = new AlertDialog.Builder(this).create();
    	ad.setTitle(getResources().getString(R.string.app_name) + " (" + sVersion + ")");
    	ad.setMessage(getResources().getString(R.string.txtAbout));
    	ad.setIcon(R.drawable.ic_menu_info_details);
    	ad.setButton("Close", new DialogInterface.OnClickListener() {
    	      public void onClick(DialogInterface dialog, int which) {
    	 
    	       dialog.cancel();
    	 
    	    }
    	});
    	ad.show();
    }
    
    // show the monthly tide table
    public void ShowDiveTable() {

    	startActivity(new Intent(planner.this, divetable.class));
    	
    }
}
